<?php
namespace WechatSDK\Components;

use WechatSDK\Lib\Tools;
require_once ('Common.php');
require_once ('Imessage.php');
/**
 * 群发消息组件
 * @author guibinyu
 * @date 2017-06-15 04:14:50
 */
class MassMessage   extends Common implements Imessage
{
    const MASS_SEND_URL = '/message/mass/send?';
    const MASS_SEND_GROUP_URL = '/message/mass/sendall?';
    const MASS_DELETE_URL = '/message/mass/delete?';
    const MASS_PREVIEW_URL = '/message/mass/preview?';
    const MASS_QUERY_URL = '/message/mass/get?';
    
    const MSGTYPE_MP_VIDEO = 'mpvideo';
     const MSGTYPE_MP_NEWS = 'mpnews';
    private  $touser;
     private $message;
     private $sendall = 0;
	function __construct($appid,$secret,$token)
	{
        parent::__construct($appid,$secret,$token);
	}

	function __destruct()
	{
        
	}
      /**
     * 设置接收信息用户
     * @param type array $userParams
     * @return type
       * 格式2
       * {
      "is_to_all":false,
      "tag_id":2
       * }
       * 格式1
        * [
         "OPENID1",
         "OPENID2"
        ]
   
     */
    public function setTouser($users)
    {
         $this->touser = $users;
         $this->sendall = isset($this->touser['filter']) ? 1 :0 ;
         $this->Message($this->touser);
         return $this;
    }
    /**
     * 获取接收信息的用户
     * @return type
     */
    public function getToUser()
    {
        return $this->touser;
    }
    /**
     * 发送文本消息
     * @param type $text 文本消息内容
     * @return array
     * {
            "touser":[
             "OPENID1",
             "OPENID2"
            ],
             "msgtype": "text",
             "text": { "content": "hello from boxer."}
         }

         {
            "filter":{
               "is_to_all":false,
               "tag_id":2
            },
            "text":{
               "content":"CONTENT"
            },
             "msgtype":"text"
         }
     */
    public function text($text)
	{
        $msg = array(
            'msgtype'      => self::MSGTYPE_TEXT,
            'text' => array(
                 'content'  => $text,
             ),
        );
        $this->Message($msg,TRUE);
        return $this;
	}
    /**
     * 发送图片消息
     * @param type $media_id 发送的图片/语音/视频/图文消息（点击跳转到图文消息页）的媒体ID
     * @return type
     */
	public function image($media_id = '')
	{
        $msg = array(
            'msgtype'      => self::MSGTYPE_IMAGE,
            'image' => array(
                 'media_id'  => $media_id,
             ),
        );
        $this->Message($msg,TRUE);
        return $this;
	}
    /**
     * 发送语音消息
     * @param type $media_id 发送的图片/语音/视频/图文消息（点击跳转到图文消息页）的媒体ID
     * @return type
     */
	public function voice($media_id = '')
	{
         $msg = array(
            'msgtype'      => self::MSGTYPE_VOICE,
            'voice'        => array(
                'media_id' => $media_id
            ),
        );
        $this->Message($msg,TRUE);
        return $this;
	}
    /**
     * 发送视频消息
     * @param type $media_id 发送的图片/语音/视频/图文消息（点击跳转到图文消息页）的媒体ID
     * @param type $thumb_media_id 缩略图的媒体ID
     * @param type $title 图文消息/视频消息/音乐消息的标题
     * @param type $description 图文消息/视频消息/音乐消息的描述
     * array(
                'media_id'     => $media_id,
//                'thumb_media_id'  => $thumb_media_id,
                'title' => $title,
                'description'=> $description,
            )
     * @return type
     */
	 public function video($video) {
        $msg = array(
            'msgtype'      => self::MSGTYPE_MP_VIDEO,
            'mpvideo'        => $video,
        );
         $this->Message($msg,TRUE);
        return $this;
    }
  
    /**
     * 发送图文消息（点击跳转到外链） 图文消息条数限制在8条以内，注意，如果图文数超过8，则将会无响应。
     * @param type $newsData
     * @return type  "news":{
        "articles": [
         {
             "title":"Happy Day",
             "description":"Is Really A Happy Day",
             "url":"URL",
             "picurl":"PIC_URL"
         },
         {
             "title":"Happy Day",
             "description":"Is Really A Happy Day",
             "url":"URL",
             "picurl":"PIC_URL"
         }
         ]
     */
	 public function news($news = array()) {
       exit('please use mpnews');
    }
     /**
     * 发送图文消息（点击跳转到图文消息页面） 图文消息条数限制在8条以内，注意，如果图文数超过8，则将会无响应。
     * @param type $media_id 发送的图片/语音/视频/图文消息（点击跳转到图文消息页）的媒体ID
     * @return type
     */
     public function mpnews($media_id) {
        $msg = array(
            'touser'   => $this->getToUser(),
            'msgtype'      => self::MSGTYPE_MP_NEWS,
            'mpnews'     => array(
                'media_id' => $media_id
            ),
        );
        $this->Message($msg);
        return $this;
    }

      /**
     *  高级群发消息, 删除群发图文消息(认证后的订阅号可用)
     * @param string $msg_id 消息ID
     * @return bool
     */
	public function del($msg_id)
	{
          if (!$this->access_token && !$this->getAccessToken()) {
            return false;
        }
        $result = Tools::httpPost(self::API_URL_PREFIX . self::MASS_DELETE_URL . "access_token={$this->access_token}", Tools::json_encode(array('msg_id' => $msg_id)));
         $result = $this->parsing($result);
        return $result;
	}
/**
     * 高级群发消息, 预览群发消息(认证后的订阅号可用)
     *     注意：视频需要在调用uploadMedia()方法后，再使用 uploadMpVideo() 方法生成，
     *           然后获得的 mediaid 才能用于群发，且消息类型为 mpvideo 类型。
     * @param type $data
     * @消息结构
     * {
     *     "touser"=>"OPENID",
     *      "msgtype"=>"mpvideo",
     *      // 在下面5种类型中选择对应的参数内容
     *      // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
     *      // text => array ( "content" => "hello")
     * }
     * @return bool|array
     */
	public function preview($data)
	{
         if (!$this->access_token && !$this->getAccessToken()) {
            return false;
        }
        $result = Tools::httpPost(self::API_URL_PREFIX . self::MASS_PREVIEW_URL . "access_token={$this->access_token}", Tools::json_encode($data));
        $result = $this->parsing($result);
        return $result;
	}
/**
     * 高级群发消息, 查询群发消息发送状态(认证后的订阅号可用)
     * @param string $msg_id 消息ID
     * @return bool|array
     * {
     *     "msg_id":201053012,     //群发消息后返回的消息id
     *     "msg_status":"SEND_SUCCESS" //消息发送后的状态，SENDING表示正在发送 SEND_SUCCESS表示发送成功
     * }
     */
	public function query()
	{
         if (!$this->access_token && !$this->getAccessToken()) {
            return false;
        }
        $result = Tools::httpPost(self::API_URL_PREFIX . self::MASS_QUERY_URL . "access_token={$this->access_token}", Tools::json_encode(array('msg_id' => $msg_id)));
        $result = $this->parsing($result);
        return $result;
	}

    public function message($msg = '', $append = false) {
        if (is_null($msg)) 
        {
            $this->message = array();
        } 
        elseif (is_array($msg)) 
        {
            if ($append) 
            {
                $this->message = array_merge($this->message, $msg);
            } else 
            {
                $this->message = $msg;
            }
            return $this->message;
        }
        
        return $this->message;
    }
/**
     * 高级群发消息, 根据群组id群发图文消息(认证后的订阅号可用)
     *       注意：视频需要在调用uploadMedia()方法后，再使用 uploadMpVideo() 方法生成，
     *           然后获得的 mediaid 才能用于群发，且消息类型为 mpvideo 类型。
     * @param array $data 消息结构
     * {
     *     "filter"=>array(
     *         "is_to_all"=>False,     //是否群发给所有用户.True不用分组id，False需填写分组id
     *         "group_id"=>"2"     //群发的分组id
     *     ),
     *      "msgtype"=>"mpvideo",
     *      // 在下面5种类型中选择对应的参数内容
     *      // mpnews | voice | image | mpvideo => array( "media_id"=>"MediaId")
     *      // text => array ( "content" => "hello")
     * }
     * @return bool|array
     */
    public function send($send=true,$message=array()) 
    {
        if (!$this->access_token && !$this->getAccessToken()) {
            return false;
        }
         if (empty($message)) {
            if (empty($this->message)) {   //防止不先设置回复内容，直接调用reply方法导致异常
                return false;
            }
            $message = $this->message;
        }
        if (!$send) 
        {
            return $message;
        }
//        dump($message);
//        dump(Tools::json_encode($message));
//        exit();
        $obj = $this->sendall ?  self::MASS_SEND_GROUP_URL : self::MASS_SEND_URL ;
        $result = Tools::httpPost(self::API_URL_PREFIX . $obj  . "access_token={$this->access_token}", Tools::json_encode($message));
        $result = $this->parsing($result);
        return $result;
    }
   

}
?>